// 获取应用实例
const app = getApp()

Page({

    data: {
        list_data: [],
        list_total: 0,
        now_page: 0,
        keywords: '',
        limit: 50,
        cate_show_data: [],
        cate_all_data: [],
        sel_index_arr: [0, 0, 0],
        choose_index_arr: [],
        choose_id_arr: [],
        choose_cate_name: [],
        year: [],
        choose_status: '',
        is_show_shade: 0,
        is_show_shuaixun: 0,
        year_arr: [],
        choose_year_index: 0,
        status_arr: [
            {id: 1, name: '全部', status: 0},
            {id: 2, name: '采购未完成', status: 1},
            {id: 3, name: '到料未完成', status: 2},
        ],
        choose_status_index: 0,
        choose_status_name: '',
        season_list: [],
        summary_list: [],
        table_head: [
            // {id: 1, name: '图片', field: 'images', is_checked: false, width: 70, show_user: [0]},
            // {id: 2, name: '简码', field: 'template_no', is_checked: false, width: 100, show_user: [0]},
            {id: 3, name: '下单日', field: 'created_date', is_checked: true, width: 120, show_user: [0,1,2,3]},
            {id: 6, name: '下单数', field: 'order_num', is_checked: true, width: 110, show_user: [0,2,3]},
            {id: 8, name: '性质', field: 'type', is_checked: true, width: 80, show_user: [0,1,2,3]},
            {id: 4, name: '采购进度', field: 'jindu', is_checked: true, width: 120, show_user: [0,1]},
            {id: 5, name: '采购需求数', field: 'total_need_num', is_checked: true, width: 140, show_user: [0,1,3]},
            {id: 6, name: '已采购数', field: 'total_caigou_num', is_checked: true, width: 150, show_user: [0,1]},
            {id: 7, name: '未采购数', field: 'unreceived', is_checked: true, width: 150, show_user: [0,1]},
            {id: 16, name: '入库进度', field: 'shou_jindu', is_checked: true, width: 180, show_user: [0,3]},

            {id: 10, name: '入库数', field: 'shou_num', is_checked: true, width: 180, show_user: [0,3]},
            {id: 11, name: '未入数', field: 'no_shou_num', is_checked: true, width: 180, show_user: [0,3]},
            // {id: 3, name: 'bom总数', field: 'total_bom_num', is_checked: true, width: 120, show_user: [0]},
            // {id: 7, name: '未采购', field: 'less_purchase', is_checked: true, width: 120, show_user: [0]},
            // {id: 4, name: '已采购', field: 'purchase_bom_num', is_checked: true, width: 120, show_user: [0]},
            // {id: 5, name: '无需采购', field: 'no_purchase', is_checked: true, width: 120, show_user: [0]},
            // {id: 9, name: '无需采购总量', field: 'no_total_need_num', is_checked: true, width: 180, show_user: [0,1]},
            {id: 9, name: '外发工厂', field: 'outgoing_factory', is_checked: true, width: 180, show_user: [0,2]},

            {id: 15, name: '发料进度', field: 'send_jindu', is_checked: true, width: 180, show_user: [0,3]},

            // {id: 14, name: '需发出数', field: 'shou_num', is_checked: true, width: 180, show_user: [0,3]},
            {id: 12, name: '已发数', field: 'new_send_num', is_checked: true, width: 180, show_user: [0,3]},
            {id: 13, name: '未发数', field: 'no_send_num', is_checked: true, width: 180, show_user: [0,3]},
            // {id: 6, name: '已到齐', field: 'reach_num', is_checked: true, width: 120, show_user: [0, 1]},
        ],
        table_scroll_left: 0,
        person_list: [],
        outgoing_user: -1,
        outgoing_user_name: '',
        table_user_type: 0, // 0 全部 1采购 2外发人 3仓库
        table_user_name: '全部',
        table_role_arr: [
            {id: 1, name: '全部', value: 0},
            {id: 2, name: '采购', value: 1},
            {id: 3, name: '外发人', value: 2},
            {id: 4, name: '仓库', value: 3},
        ],
        allow_change_role: true,
        // 排序方式
        list_order_method: {
            total_bom_id: 'desc'
        },
    },

    onLoad(options) {
        wx.setNavigationBarTitle({
            title: '物料跟踪'
        });
        var __this = this;
        // 设置筛选球位置
        setTimeout(function () {
            // 获取宽高
            __this.setData({
                menu_x: wx.getSystemInfoSync().windowWidth - 60,
                menu_y: wx.getSystemInfoSync().windowHeight - 70,
            });
        }, 100);
        // 生成年份
        this.get_year_list();
        // 获取数据
        // this.get_list_data();
        // 获取汇总数据
        this.get_summary_data();
        // 获取分类
        this.get_cate_list();
        // 获取季节
        this.get_season_list();
        // 获取外发人
        this.get_person_list();
    },

    // 页面触底时执行
    onReachBottom: function () {
        this.get_list_data();
    },

    // 表格滑动结束
    tr_boxs_scroll_end: function (e) {
        var __this = this;
        setTimeout(function () {
            __this.setData({
                table_scroll_left: e.detail.scrollLeft
            });
        }, 180);
    },

    // 获取列表数据
    get_list_data: function (is_show_loading = true, is_search = 0) {
        var __this = this;
        // 验证
        if ((this.data.list_data.length >= this.data.list_total) && this.data.now_page > 0) {
            return false;
        }
        // 组装参数
        var req_data = this.get_request_param();
        req_data.page = this.data.now_page + 1;
        req_data.is_sum = 1;
        req_data.limit = this.data.limit;
        console.log(req_data);
        // 组装排序
        var order_arr = [];
        for( let key in this.data.list_order_method ){
            order_arr.push(key + ',' + this.data.list_order_method[key]);
        }
        var req_url = 'admin/TotalBom/index';
        if (order_arr.length > 0) {
            req_url += '?order=' + order_arr.join(',');
        }
        console.log(req_url);
        // 发起请求
        var result = app.request_api(req_url, req_data, is_show_loading);
        result.then(res => {
            console.log(res)
            if (is_search == 1) {
                this.setData({
                    list_data: [],
                    now_page: 0,
                    list_total: 0,
                })
            }
            if (this.data.allow_change_role) {
                // 验证显现字段
                this.data.table_head.forEach(function (item, index) {
                    if (item.show_user.includes(parseInt(res.table_user_type))) {
                        __this.data.table_head[index].is_checked = true;
                    } else {
                        __this.data.table_head[index].is_checked = false;
                    }
                })
            }
            var sel_role_index = this.data.table_role_arr.findIndex(obj => obj.value === res.table_user_type);
            // 重设data
            this.setData({
                list_data: this.data.list_data.concat(res.list),
                list_total: res.total,
                now_page: this.data.now_page + 1,
                table_user_type: res.table_user_type,
                table_user_name: sel_role_index > -1 ? this.data.table_role_arr[sel_role_index].name : '切换角色',
                table_head: this.data.table_head
            });
        })
    },

    // 获取外发人
    get_person_list: function () {
        // 发起请求
        var result = app.request_api('admin/template/getOutgoings', {}, false, 'GET');
        result.then(res => {
            console.log(res)
            var person_list = [{uid: 0, realname: '全部'}];
            this.setData({
                person_list: person_list.concat(res.list)
            });
        });
    },

    // 获取分类
    get_cate_list: function () {
        // 发起请求
        var result = app.request_api('admin/GoodsCategory/index', {
            is_mini: 1
        }, false);
        result.then(res => {
            // console.log(res);
            if (res.list.length > 0) {
                res.list.forEach(function (item, index) {
                    // 往子项里追加全部
                    res.list[index].children.unshift({
                        id: 0,
                        category_name: '全部',
                        children: [],
                    });
                    res.list[index].children.forEach(function (item2, index2) {
                        res.list[index].children[index2].children.unshift({
                            id: 0,
                            category_name: '全部'
                        });
                    });
                });
                this.setData({
                    cate_show_data: [res.list, res.list[0].children, res.list[0].children[0].children],
                    cate_all_data: res.list
                });
                // console.log(res.list)
            }
        });
    },

    // 分类值变化时
    CateValueChange: function (e) {
        // console.log(e);
        var cate_show_data = this.data.cate_show_data;
        var choose_index_arr = e.detail.value;
        var choose_cate_name = cate_show_data[0][choose_index_arr[0]].category_name + ' - ' + cate_show_data[1][choose_index_arr[1]].category_name  + ' - ' + cate_show_data[2][choose_index_arr[2]].category_name;
        // 更改data
        this.data.choose_id_arr.push([cate_show_data[0][choose_index_arr[0]].id, cate_show_data[1][choose_index_arr[1]].id, cate_show_data[2][choose_index_arr[2]].id]);
        this.data.choose_index_arr.push(choose_index_arr);
        this.data.choose_cate_name.push(choose_cate_name);
        this.setData({
            choose_id_arr: this.data.choose_id_arr,
            choose_index_arr: this.data.choose_index_arr,
            choose_cate_name: this.data.choose_cate_name,
            list_data: [],
            now_page: 0,
            list_total: 0,
        });
        // 重新请求数据
        this.get_summary_data(false);
    },

    // 分类列变化时
    CateColumnChange: function (e) {
        // console.log(e);
        var cate_all_data = this.data.cate_all_data;
        var cate_show_data = this.data.cate_show_data;
        var sel_index_arr = this.data.sel_index_arr;
        var index = e.detail.value;
        if (e.detail.column == 0) {
            // 一级分类改变时
            this.data.cate_show_data[1] = cate_all_data[index].children;
            this.data.cate_show_data[2] = cate_all_data[index].children[0].children;
            sel_index_arr = [index, 0, 0];
        }
        if (e.detail.column == 1) {
            // 二级分类改变时
            this.data.cate_show_data[2] = cate_show_data[1][index].children;
            sel_index_arr[1] = index;
            sel_index_arr[2] = 0;
        }
        if (e.detail.column == 2) {
            // 三级分类改变时
            sel_index_arr[2] = index;
        }
        // 重新渲染
        this.setData({
            cate_show_data: this.data.cate_show_data,
            sel_index_arr: sel_index_arr
        });
    },

    // 显示筛选
    shuai_xuan_toggle: function () {
        var is_show_shade = true;
        var is_show_shuaixun = true;
        if (this.data.is_show_shuaixun) {
            is_show_shade = false;
            is_show_shuaixun = false;
        }
        this.setData({
            is_show_shade: is_show_shade,
            is_show_shuaixun: is_show_shuaixun,
        });
    },

    // 关闭筛选
    close_shuaixun: function () {
        this.setData({
            is_show_shade: false,
            is_show_shuaixun: false,
        });
    },

    // 生成年份
    get_year_list: function () {
        // 当前年
        var now_year = new Date().getFullYear();
        var year_arr = [];
        // 取前后五年
        for (let i = (now_year - 5); i < (now_year + 6); i++) {
            year_arr.push(i);
        }
        this.setData({
            year_arr: year_arr,
            choose_year_index: 5
        });
    },

    // 年份改变时
    yearChange: function (e) {
        // 验证是否在数组中
        if (this.data.year.findIndex(obj => obj === this.data.year_arr[e.detail.value]) > -1) {
            wx.showToast({
                title: '已选择过此年份',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        this.data.year.push(this.data.year_arr[e.detail.value]);
        this.setData({
            year: this.data.year,
            choose_year_index: e.detail.value,
            list_data: [],
            now_page: 0,
            list_total: 0,
        });
        // 重新获取
        this.get_summary_data(false);
    },

    // 外发人变化时
    personChange: function (e) {
        this.setData({
            outgoing_user : this.data.person_list[e.detail.value].uid,
            outgoing_user_name : this.data.person_list[e.detail.value].realname,
            list_data: [],
            now_page: 0,
            list_total: 0,
        });
        // 重新获取
        this.get_summary_data(false);
    },

    // 选择状态时
    statusChange: function (e) {
        this.setData({
            choose_status_name: this.data.status_arr[e.detail.value].name,
            choose_status_index: e.detail.value,
            list_data: [],
            now_page: 0,
            list_total: 0,
        });
        // 重新获取
        this.get_summary_data(false);
    },

    // 获取季节接口
    get_season_list: function () {
        var __this = this;
        var result = app.request_api('admin/TotalBom/getSeason', {}, false);
        result.then(res => {
            console.log(res);
            if (res.length > 0) {
                res.forEach(function (item, index) {
                    res[index].is_checked = false;
                    res[index].children.forEach(function (item_son, index_son) {
                        res[index].children[index_son].is_checked = false;
                    });
                });
                this.setData({
                    season_list: res
                });
            }
        });
    },

    // 选中季节时
    choose_season: function (events) {
        var __this = this;
        var pindex = events.currentTarget.dataset.pindex;
        var is_check = true;
        if (__this.data.season_list[pindex].is_checked) {
            is_check = false;
        }
        __this.data.season_list[pindex].is_checked = is_check;
        // 如果是选中则需将下级也选中
        __this.data.season_list[pindex].children.forEach(function (item, index) {
            __this.data.season_list[pindex].children[index].is_checked = is_check;
        });
        this.setData({
            list_data: [],
            now_page: 0,
            list_total: 0,
            season_list: __this.data.season_list
        });
        console.log(this.data.season_list);
        // 重新请求数据
        this.get_summary_data(false);
    },

    // 选中季节时
    choose_season_son: function (events) {
        var __this = this;
        var pindex = events.currentTarget.dataset.pindex;
        var sindex = events.currentTarget.dataset.sindex;
        var is_check = true;
        if (__this.data.season_list[pindex].children[sindex].is_checked) {
            is_check = false;
        }
        __this.data.season_list[pindex].children[sindex].is_checked = is_check;
        // 取消时将父级也取消 选中时验证是否要选中父级
        if (!is_check) {
            __this.data.season_list[pindex].is_checked = is_check;
        } else {
            var is_all_checked = 1;
            __this.data.season_list[pindex].children.forEach(function (item, index) {
                if (!__this.data.season_list[pindex].children[index].is_checked) {
                    is_all_checked = 0;
                }
            })
            if (is_all_checked == 1) {
                __this.data.season_list[pindex].is_checked = is_check;
            }
        }
        this.setData({
            list_data: [],
            now_page: 0,
            list_total: 0,
            season_list: __this.data.season_list
        });
        console.log(this.data.season_list);
        // 重新请求数据
        this.get_summary_data(false);
    },

    // 获取汇总数据
    get_summary_data: function (is_show_loading = true, is_search = 0) {
        var __this = this;
        var req_data = this.get_request_param();
        console.log(req_data);
        // 查询
        var result = app.request_api('admin/total_bom/getSummary', req_data, true);
        result.then(res => {
            console.log(res);
            this.setData({
                summary_list: res
            })
            // 获取列表
            this.get_list_data(is_show_loading, is_search);
        });
    },

    // 组装查询参数
    get_request_param: function () {
        var __this = this;
        var req_data = {};
        // 年份
        if (this.data.year.length > 0) {
            req_data.year = this.data.year;
        }
        // 分类
        var category1 = [];
        var category2 = [];
        var category3 = [];
        if (this.data.choose_id_arr.length > 0) {
            this.data.choose_id_arr.forEach(function (item, index) {
                category1.push(item[0]);
                category2.push(item[1]);
                category3.push(item[2]);
            });
        }
        if (category1.length > 0) {
            req_data.category1 = category1;
        }
        if (category2.length > 0) {
            req_data.category2 = category2;
        }
        if (category3.length > 0) {
            req_data.category3 = category3;
        }
        // 状态
        req_data.status = this.data.status_arr[this.data.choose_status_index].status;
        // 外发人
        if (this.data.outgoing_user > -1) {
            req_data.outgoing_user = this.data.outgoing_user;
        }
        // 组装季节
        var seasons = [];
        __this.data.season_list.forEach(function (item, index) {
            item.children.forEach(function (item_son, index_son) {
                if (item_son.is_checked) {
                    seasons.push(item_son.name);
                }
            });
        });
        if (seasons.length > 0) {
            req_data.seasons = seasons;
        }
        // 关键词
        if (this.data.keywords.trim() != '') {
            req_data.quick_search = this.data.keywords.trim();
        }
        // 返回
        return req_data;
    },

    // 预览图片
    PreviewImage: function (events) {
        var src = events.currentTarget.dataset.src;
        // 调用
        wx.previewImage({
            current: src,
            urls: [src]
        })
    },

    // 跳转到详情页
    GoDetail: function (events) {
        var __this = this;
        var total_bom_id = events.currentTarget.dataset.id;
        var template_no = events.currentTarget.dataset.no;
        var table_user_type = this.data.table_user_type;
        // 打开详情页面
        wx.navigateTo({
            url: '/pages/wuliao_follow_detail/wuliao_follow_detail?total_bom_id=' + total_bom_id + '&template_no=' + template_no + '&table_user_type=' + table_user_type,
        });
    },

    // 搜索输入
    GoSearch: function (events) {
        var keywords = events.detail.value.trim();
        this.setData({
            keywords: keywords,
            list_data: [],
            now_page: 0,
            list_total: 0,
        });
        this.get_summary_data(false, 1);
    },

    // 删除年份
    DeleteYear: function (e) {
        var index = e.currentTarget.dataset.index;
        // 删除对应年份
        this.data.year.splice(index, 1);
        this.setData({
            year: this.data.year,
            list_data: [],
            now_page: 0,
            list_total: 0,
        })
        // 重新请求数据
        this.get_summary_data(false);
    },

    // 删除分类
    DeleteCategory: function (e) {
        var index = e.currentTarget.dataset.index;
        this.data.choose_id_arr.splice(index, 1);
        this.data.choose_index_arr.splice(index, 1);
        this.data.choose_cate_name.splice(index, 1);
        this.setData({
            choose_id_arr: this.data.choose_id_arr,
            choose_index_arr: this.data.choose_index_arr,
            choose_cate_name: this.data.choose_cate_name,
            list_data: [],
            now_page: 0,
            list_total: 0,
        })
        // 重新请求数据
        this.get_summary_data(false);
    },

    // 角色切换时
    tableRoleChange: function (e) {
        var __this = this;
        var index = parseInt(e.detail.value);
        var table_user_type = this.data.table_role_arr[index].value;
        // 重组表头
        this.data.table_head.forEach(function (item, index2) {
            if (item.show_user.includes(parseInt(table_user_type))) {
                __this.data.table_head[index2].is_checked = true;
            } else {
                __this.data.table_head[index2].is_checked = false;
            }
        });
        // 重设data
        this.setData({
            table_user_type: table_user_type,
            table_user_name: this.data.table_role_arr[index].name,
            table_head: this.data.table_head,
            allow_change_role: false
        });
        wx.showToast({
            title: '切换成功',
            icon: 'none',
            duration: 1500,
        });
        return false;
    },

    // 更改排序
    listOrderChange: function (e) {
        var order = 'desc';
        if (this.data.list_order_method.total_bom_id == 'desc') {
            order = 'asc';
        }
        this.data.list_order_method.total_bom_id = order;
        // 重设data
        this.setData({
            list_order_method: this.data.list_order_method,
            list_data: [],
            now_page: 0,
            list_total: 0,
        });
        // 重新请求数据
        this.get_list_data(true);
    },



})